package com.wentao.mall.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wentao.mall.commons.Constant;
import com.wentao.mall.commons.Result;
import com.wentao.mall.exception.MallExceptionEnum;
import com.wentao.mall.model.po.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomerFilter implements Filter {
    //提取Session中的user
    public static User currentUser=null;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        //设置响应数据为json格式，前后端分离
        resp.setContentType("application/json;charset=utf-8");
        //获得用户信息
        currentUser = (User)req.getSession().getAttribute(Constant.CURRENT_USER);
        //jackson转换json数据
        ObjectMapper objectMapper = new ObjectMapper();
        //未登录过滤
        if (currentUser==null){
            String result = objectMapper.writeValueAsString(Result.error(MallExceptionEnum.NEED_LOGIN));
            resp.getWriter().write(result);
            return;             //return则不放行，过滤请求
        }

        filterChain.doFilter(req,resp);
    }
}
